package com.nolydake.swingnote.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;

import org.apache.log4j.Logger;

public abstract class AbstractDao implements IBaseDao {

    /** 日志 */
    private static final Logger LOG = Logger.getLogger(AbstractDao.class);

    protected Connection connection = null;

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    public Connection getConnection() {
        return this.connection;
    }

    protected abstract String getTableName();

    protected abstract Map<String, Column> getColumns();

    public String validateDB() {

        if (!tabbleIsExist(getTableName())) {
            return "数据表" + getTableName() + "丢失！";
        }

        return null;
    }

    public String initDB() {

        Statement statement;

        try {
            statement = connection.createStatement();
            statement.setQueryTimeout(30);

            // String drop = "drop table if exists " + getTableName();
            StringBuffer create = new StringBuffer();
            create.append("create table if not exists " + getTableName());
            create.append("(");

            boolean isStart = false;
            Map<String, Column> columns = getColumns();
            for (String key : columns.keySet()) {

                if (isStart) {
                    create.append(",");
                }

                isStart = true;

                Column column = columns.get(key);

                create.append(key);
                create.append(" ");
                create.append(column.columnType);

                if (column.isPrimaryKey) {
                    create.append(" PRIMARY KEY");
                }
            }

            create.append(")");

            if (LOG.isDebugEnabled()) {
                LOG.debug(create.toString());
            }

            statement.executeUpdate(create.toString());

            initData();

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;

    }

    /**
     * 初始化数据
     * 
     * @return 错误消息
     */
    protected String initData() {
        return null;
    }

    /**
     * 判断数据表是否存在
     * 
     * @param tableName
     * @return
     */
    public boolean tabbleIsExist(String tableName) {

        if (tableName == null) {
            return false;
        }

        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {

            String sql = "select count(*) as c from sqlite_master where type='table' and name ='" + tableName.trim()
                    + "' ";

            // String sql = "select count(*) as c from " + tableName.trim();

            if (LOG.isDebugEnabled()) {
                LOG.debug(sql);
            }

            stmt = connection.prepareStatement(sql);
            rs = stmt.executeQuery();

            if (rs.next()) {

                int result = rs.getInt(1);

                if (LOG.isDebugEnabled()) {
                    LOG.debug("返回值" + result);
                }

                return result > 0;
            }

            return false;

        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return false;
        }
    }
}
